package com.sth.shishan;

import org.junit.Test;
import redis.clients.jedis.Jedis;

/**
 * @Author: sitianhong
 * @Description: 支持超时自动释放锁的分布式锁案例
 * @Since: create in 2021/6/13 0013 20:50
 */
public class RedisDemo11 {
    Jedis jedis = new Jedis("127.0.0.1", 6378);

    @Test
    public void demo2() throws InterruptedException {
        long lock = lock("test_lock", "test_value", 1);
        System.out.println("第一次加锁 " + lock);
        Thread.sleep(2 * 1000);
        System.out.println("第二次加锁 " + lock("test_lock", "test_value", 60));
    }

    // 加锁
    public long lock(String key, String value, int timeout) {
        Long result = jedis.setnx(key, value);
        jedis.expire(key, timeout);
        return result;
    }

    // 解锁
    public void unLock(String key) {
        jedis.del(key);
    }
}
